<template>
  <el-dialog :visible.sync="visible" class="mod-config" width="80%" top="8vh">
    <basic-container>
    <!--<div class="tabletext mb10 font18 ml30">不可导入数据共<span class="red font22">{{ errCount }}</span>条</div>-->
      <div class="boxsty zhiBiao" >
        <div class="avue-crud">
          <el-table :data="dataList" v-loading="dataListLoading" stripe border tooltip-effect="light" height="490">
            <el-table-column fixed label="序号" align="center" width="80">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <!--<el-table-column prop="errIndex" label="错误行" width="100"></el-table-column>-->
            <el-table-column fixed prop="ryCode" label="人员编号" width="120"></el-table-column>
            <el-table-column fixed prop="ryXm" label="姓名"></el-table-column>
            <el-table-column prop="errMsg" label="错误信息" width="150">
              <template slot-scope="scope">
                <span style="color: red">{{scope.row.errMsg}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="ryGzdwCode" label="工作单位编号" width="180"></el-table-column>
            <el-table-column prop="ryGzdw" label="工作单位" width="180"></el-table-column>
            <el-table-column prop="ryZwgz" label="职务或工种" width="280"></el-table-column>
            <el-table-column prop="ryXzjb" label="行政级别" width="120"></el-table-column>
            <el-table-column prop="llKssj" :formatter="formater" label="开始日期" width="120"></el-table-column>
            <el-table-column prop="llJssj" :formatter="formater" label="结束日期" width="120"></el-table-column>
<!--            <el-table-column prop="jjFfDeptCode" label="奖金发放部门编号" width="180"></el-table-column>
            <el-table-column prop="jjFfDeptName" label="奖金发放部门名称" width="180"></el-table-column>-->
            <el-table-column prop="ryJszc" label="技术职称" width="180"></el-table-column>
            <el-table-column prop="ryJnjb" label="技能级别" width="180"></el-table-column>
            <el-table-column prop="jjFfMonth" label="任职时长" width="120"></el-table-column>

            <el-table-column prop="llBz" label="备注" width="180"></el-table-column>
          </el-table>
        </div>
        <span style="float: right;margin-top: 27px;">
          <el-button @click="allImport()" type="primary">全部导入</el-button>
        </span>
<!--        <div style="margin-top:20px">-->
<!--          <el-pagination background layout="total,prev, pager, next,jumper" @current-change="handleCurrentChange"-->
<!--                         :current-page="page.currentPage" :page-size="page.pageSize" :total="page.total">-->
<!--          </el-pagination>-->
<!--        </div>-->
      </div>
      <!-- 弹窗, 新增 / 修改 -->
      <table-form v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="callockGetList"></table-form>
    </basic-container>
  </el-dialog>
</template>

<script>
import { saveBath,fetchList} from '@/api/jiangjin/jiangjinryllb'
import TableForm from './errorForm'
import store from '@/store'
import request from '@/router/axios'
import {  mapGetters} from 'vuex'
import {getRyxxListPermissionNone} from '@/api/admin/sysryxxb';
import {getTreeList} from '@/api/admin/dept'
import {remote as remoteDict } from '@/api/admin/dict'


export default {
  data() {
    return {
      visible: false,
      dataList: [],
      dataAllList:[],

      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      addOrUpdateVisible: false,
      removeIndex: '',
      xpList: [],
      loading: '',
      errCount: 0,
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20, // 每页显示多少条,
        isAsc: false // 是否倒序
      },
      dataRyList:[],
      listTree:[],
      userZjOptions:[],
    }
  },
  components: {
    TableForm
  },

  computed: {
    ...mapGetters(['permissions'])
  },

  methods: {
    // 获取数据列表
    getDataList(res) {
      this.visible = true;
      this.dataListLoading = true;

      this.dataList = [];
      this.dataAllList = [];

      this.dataAllList = res.data.data;
      this.setDataColumn();


      fetchList().then( res => {
        this.dataRyList = [];
        this.dataRyList = res.data.data.records;
       // console.log(this.dataRyList);
      })

      getTreeList(this.listQuery).then(response => {
        this.listTree = [];
        this.listTree = response.data.data;
        ////console.log(this.listTree);
      })

      remoteDict("user_zj").then(response => {
        this.userZjOptions = [];
        this.userZjOptions = response.data.data;
        ////console.log(this.userZjOptions);
      })

      // this.dataList = this.dataAllList;


      // this.errCount = res.data.msg;
      // this.getPagingShow(this.dataList)
      this.dataListLoading = false
    },

    //设置其他错误字段
    setDataColumn(){
      console.log(JSON.stringify(this.dataAllList))
      // ryXzjbBh

      for(let i=0;i<this.dataAllList.length;i++){
        if(this.dataAllList[i]["ryCode"].toString().trim() ==="" &&
          this.dataAllList[i]["ryXm"].toString().trim() ==="" &&
          this.dataAllList[i]["ryGzdwCode"].toString().trim() ==="" &&
          this.dataAllList[i]["ryXzjb"].toString().trim() ==="" &&
          this.dataAllList[i]["llKssj"] === undefined &&
          this.dataAllList[i]["llJssj"] === undefined &&
          // this.dataAllList[i]["jjFfDeptCode"].toString().trim() ==="" &&
           this.dataAllList[i]["jjFfMonth"] === undefined){
        }else {
          this.dataList.push(this.dataAllList[i])
        }
      }

      for(let i=0;i<this.dataList.length;i++){
        if(this.dataList[i]["llKssj"] === undefined){
          this.$set(this.dataList[i],"llKssj","");
        }
        if(this.dataList[i]["llJssj"] === undefined){
          this.$set(this.dataList[i],"llJssj","");
        }


        this.$set(this.dataList[i],"ryXzjbBh","");
        this.$set(this.dataList[i],"jjFfDeptId","");

        if(this.dataList[i]["jjFfMonth"] === undefined){
          this.$set(this.dataList[i],"jjFfMonth","");
        }

        this.$set(this.dataList[i],"rglrBs",0);
      }

      ////console.log(this.dataList)
    },

    getDeptCodeByName(name){
      let lResult = "";
      this.listTree.find(u=>{
        if(u.deptName === name){
          lResult = u.deptCode;
        }
      })
      return lResult;
    },
    getDeptNameOrIdByCode(code,attribute){
      let lResult = "";
      this.listTree.find(u=>{
        if(u.deptCode === code){
          if(attribute === "id") lResult = u.deptId;
          if(attribute === "name") lResult = u.deptName;
        }
      })
      return lResult;
    },
    getDictId(dictName){
      let lResult = "";
      this.userZjOptions.find(u=>{
        if(u.label === dictName){
          lResult = u.value;
        }
      })
      return lResult;
    },
    validateDataList(){
      let lResult = "";
      //正确记录，备用
      let lRight = [];
      let sTemp = "";

      for(let i=0;i<this.dataList.length;i++){

        this.$set(this.dataList[i],"errMsg","");

        if(this.dataList[i]["ryCode"] === ""){
          this.$set(this.dataList[i],"errMsg","人员编号为空");
          continue;
        }

        sTemp = "";
        sTemp = this.getRyXm(this.dataList[i]["ryCode"]);
        if(sTemp === ""){
         // this.$set(this.dataList[i],"errMsg","人员编号查无此人");
          continue;
        }else {
          this.dataList[i]["ryXm"] = sTemp;
        }

        if(this.dataList[i]["llKssj"] === ""){
          this.$set(this.dataList[i],"errMsg","开始日期为空");
          continue;
        }

        if(this.dataList[i]["llJssj"] === ""){
          this.$set(this.dataList[i],"errMsg","结束日期为空");
          continue;
        }

        if(this.dataList[i]["ryGzdwCode"] === ""){
          this.$set(this.dataList[i],"errMsg","工作单位编号为空");
          continue;
        }

        sTemp = "";
        sTemp = this.getDeptNameOrIdByCode(this.dataList[i]["ryGzdwCode"],"name");

        if(sTemp === ""){
          this.$set(this.dataList[i],"errMsg","工作单位编号查无此部门");
          continue;
        }else {
          this.$set(this.dataList[i],"ryGzdw",sTemp);
        }


        if(this.dataList[i]["ryXzjb"] === ""){
          this.$set(this.dataList[i],"errMsg","行政级别为空");
          continue;
        }

        sTemp = "";
        sTemp = this.getDictId(this.dataList[i]["ryXzjb"]);

        if(sTemp === ""){
          this.$set(this.dataList[i],"errMsg","无此行政级别");
          continue;
        }else {
          this.$set(this.dataList[i],"ryXzjbBh",sTemp);
        }


        // if(this.dataList[i]["jjFfDeptCode"] === ""){
        //   this.$set(this.dataList[i],"errMsg","奖金发放部门编号为空");
        //   continue;
        // }
        //
        // sTemp = "";
        // sTemp = this.getDeptNameOrIdByCode(this.dataList[i]["jjFfDeptCode"],"id");
        //
        // if(sTemp === ""){
        //   this.$set(this.dataList[i],"errMsg","奖金发放部门编号查无此部门");
        //   continue;
        // }else {
        //   this.$set(this.dataList[i],"jjFfDeptId",sTemp);
        // }

        // sTemp = "";
        // sTemp = this.getDeptNameOrIdByCode(this.dataList[i]["jjFfDeptCode"],"name");
        // this.$set(this.dataList[i],"jjFfDeptName",sTemp);

        if(this.dataList[i]["jjFfMonth"] === ""){
          this.$set(this.dataList[i],"errMsg","任职时长为空");
          continue;
        }


        lRight.push(this.dataList[i]);
      }


      for(let i=0;i<this.dataList.length;i++){
        if(this.dataList[i]["errMsg"] !== ""){
          lResult = "err";
          break;
        }
      }

      return lResult;
    },

    //取得人员姓名
    getRyXm(code){
      let lXm = "";
      this.dataRyList.find(u=>{
        if(u.ryCode === code){
          lXm = u.ryXm;
        }
      })
      return lXm;
    },

    /**
     * 全部导入数据
     */
    allImport() {
      ////console.log(this.dataList);

      if(this.validateDataList() !== ""){
        return;
      }

      var _this = this;
      var msg = '';
      // if (_this.errCount > 0) {
        // msg = '存在' + _this.errCount + '条错误数据确认导入?'
      // } else {
        msg = '确认全部导入?';
      // }
      this.$confirm(msg, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {


        _this.loading = _this.$loading({
          lock: true,
          text: '人员数据导入中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        for (var i = 0; i < _this.dataList.length; i++) {
          if (_this.dataList[i].llJssj) {
            _this.dataList[i].llJssj = _this.$moment(_this.dataList[i].llJssj).format("YYYY-MM-DD")
          }
          if (_this.dataList[i].llKssj) {
            _this.dataList[i].llKssj = _this.$moment(_this.dataList[i].llKssj).format("YYYY-MM-DD")
          }
        }
        return saveBath(_this.dataList)
      }).then(data => {
        _this.visible = false
        _this.$emit('refreshDataList')
        _this.$message.closeAll()
        _this.$message.success('导入成功')
        _this.loading.close()
      })
    },

    //-------- none
    handleCurrentChange(val) {
      if (val === 1) {
        this.xpList = this.dataList.slice(0, this.page.pageSize);
      } else {
        this.xpList = this.dataList.slice(val * this.page.pageSize - this.page.pageSize, val * this.page.pageSize);
      }
      this.page.currentPage = val;
    },
    //分页
    getPagingShow(dataList) {
      this.dataList = dataList;
      this.page.total = dataList.length;
      this.xpList = this.dataList.slice(0, this.page.pageSize);
      this.page.currentPage = 1;
    },
    callockGetList(index) {
      this.dataList.splice(index, 1)
    },
    //--------


    // 新增 / 修改
    addOrUpdateHandle(r, index) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(r, index)
      })
    },
    // 删除
    deleteHandle(index) {
      var _this = this;
      this.$confirm('是否确认删除下标为' + index, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        _this.dataList.splice(index, 1)
      }).then(data => {
        this.$message.closeAll()
        this.$message.success('删除成功')

      })
    },

    nShowIndex(row, column, cellValue, index) {
      return index + 1;
    },
    handleUploadSuccess(response, file, fileList) {
      if (response.code == 0) {
        request({
          url: '/jiangjin/jiangjinryllb/fileDow/' + response.data.bucketName + '/' + response.data.fileName,
          method: 'get',
        }).then((response) => { //


        })

      } else {
        this.$message.closeAll()
        this.$message.error('上传出错：' + response.msg)
      }
    },
    formater(row, column, cellValue, index) {
      if (cellValue) {
        return this.$moment(cellValue).format("YYYY-MM-DD");
      } else {
        return cellValue;
      }
    }
  }
}

</script>
